//
//  TopScrollView.m
//  SUZHOUBANK
//
//  Created by saberLily on 16/4/14.
//  Copyright © 2016年 RuiFeng-WGCC. All rights reserved.
//

#import "TopScrollView.h"
#import "DefineHeader.h"
#import <AFNetworking/UIImageView+AFNetworking.h>
#import "DetailTopView.h"
#define ScrollView_Height 300
#define ScrollView_Width 1100
#define TotalCount 11

@interface TopScrollView()<UIScrollViewDelegate,UIGestureRecognizerDelegate>
{
    NSTimer *_timer;
    NSMutableArray *_imageUrl;
}

@property (nonatomic,strong) UIScrollView *scrollView; /**< 滚动视图 */
@property (nonatomic,strong) UIPageControl *pageControl; /**< 分页 */
@property (nonatomic,strong) UIImageView *leftImage; /**< 左图 */
//@property (nonatomic,strong) UIImageView *centerImage; /**< 中 */
@property (nonatomic,strong) UIButton *centerImage; /**< <#desc#> */
@property (nonatomic,strong) UIImageView *rightImage; /**< 右 */

@end
@implementation TopScrollView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initializeDataSource];
        [self initializeUserInterface];
        [self requestAPI];
    }
    return self;
}


#pragma mark *** Initialize methods ***
- (void)initializeDataSource {
    _imageUrl = [@[] mutableCopy];
 
}

-(void)requestAPI{
    [BaseAPIManager requestURL:@"protocol_advertisement!update.action" parameters:nil completion:^(bool success, NSInteger status, NSDictionary *data, NSError *error) {
//        [data[@"datalist"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            
//            NSArray *arr = @[@0,@1,@3,@4,@6];
//            
//            if ([arr containsObject:@(idx)]) {
//                [_imageUrl addObject:obj];
//            }else{
//            }
//        
//        }];
//        
//        self.pageControl.numberOfPages = _imageUrl.count;
//        
//        [self addSubview:self.pageControl];
//        
//        [self updateImageView];
    }];
}

-(void)updateImageView{
    
    [self.leftImage setImageWithURL:[NSURL URLWithString:_imageUrl.lastObject[@"THUMBNAILURL"]]];
//    [self.centerImage.imageView setImageWithURL:[NSURL URLWithString:_imageUrl[0]]];
    [self.centerImage setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_imageUrl[0][@"THUMBNAILURL"]]]] forState:UIControlStateNormal];
    [self.rightImage setImageWithURL:[NSURL URLWithString:_imageUrl[1][@"THUMBNAILURL"]]];
    
}

- (void)initializeUserInterface {
    
    
    [self addSubview:self.scrollView];
    [self.scrollView addSubview:self.leftImage];
    [self.scrollView addSubview:self.centerImage];
    [self.scrollView addSubview:self.rightImage];
  
    // 初始化定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(respondsToTimer) userInfo:nil repeats:YES];
    // 启动定时器
    _timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:2.0];
}

#pragma mark *** Timer methods ***
- (void)respondsToTimer {
    
    // 改变偏移
    [_scrollView setContentOffset:CGPointMake(2 * ScrollView_Width, 0) animated:YES];
    
}



#pragma mark *** UIScrollViewDelegate ***
// 开始拖动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    // 暂停timer
    _timer.fireDate = [NSDate distantFuture];
}

// 停止拖动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    // 启动timer
    _timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:2.0f];
}

// 开始减速
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (_imageUrl == nil || _imageUrl.count == 0) {
        return;
    }
    
    if (scrollView.contentOffset.x>=2*ScrollView_Width) {
        id firstObj = [_imageUrl firstObject];
        [_imageUrl removeObject:firstObj];
        [_imageUrl addObject:firstObj];
        _pageControl.currentPage = _pageControl.currentPage == _imageUrl.count - 1 ? 0 : ++ _pageControl.currentPage;
        
    }else if (scrollView.contentOffset.x<=0){
        id lastObj = [_imageUrl lastObject];
        [_imageUrl removeObject:_imageUrl.lastObject];
        [_imageUrl insertObject:lastObj atIndex:0];
        _pageControl.currentPage = _pageControl.currentPage == 0 ? _imageUrl.count - 1 : -- _pageControl.currentPage;
    }else{
        return;
    }
    [self updateImageView];
    
    [scrollView setContentOffset:CGPointMake(ScrollView_Width, 0) animated:NO];
    
}

#pragma mark *** PrivateMethods ***

-(void)respondsToTapGes{
    DetailTopView *detailView = [[DetailTopView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    detailView.detailImageUrl = _imageUrl[0][@"DETAILSURL"];
    detailView.detailTitle = _imageUrl[0][@"TITLE"];
    [detailView reloadAllData];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:detailView];
    
}

#pragma mark *** Getters ***
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        // 设置内容大小
        _scrollView.contentSize = CGSizeMake(3 * ScrollView_Width, ScrollView_Height);
        // 设置偏移量
        _scrollView.contentOffset = CGPointMake(ScrollView_Width, 0);
        // 设置能否回弹
        _scrollView.bounces = NO;
        // 设置是否分页
        _scrollView.pagingEnabled = YES;
        // 设置能否滚动
        _scrollView.scrollEnabled = YES;
        // 设置是否点击状态栏是否回到顶部
        _scrollView.scrollsToTop = YES;
        // 设置是否显示横向指示器
        _scrollView.showsHorizontalScrollIndicator = NO;
        // 设置是否显示纵向指示器
        _scrollView.showsVerticalScrollIndicator = YES;
        // 设置代理
        _scrollView.delegate = self;
        
        
    }
    return _scrollView;
}
-(UIImageView *)leftImage{
    if (!_leftImage) {
        _leftImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScrollView_Width, ScrollView_Height)];
        _leftImage.backgroundColor = [UIColor blueColor];
    }
    return _leftImage;
}
-(UIButton *)centerImage{
    if (!_centerImage) {
        _centerImage = [[UIButton alloc] initWithFrame:CGRectMake(ScrollView_Width, 0, ScrollView_Width, ScrollView_Height)];
        _centerImage.backgroundColor = [UIColor purpleColor];
        
//      [_centerImage addTarget:self action:@selector(respondsToTapGes) forControlEvents:UIControlEventTouchUpInside];
        
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(respondsToTapGes)];
        tapGes.delegate = self;
        [_centerImage addGestureRecognizer:tapGes];
        
    }
    return _centerImage;
}
-(UIImageView *)rightImage{
    if (!_rightImage) {
        _rightImage = [[UIImageView alloc] initWithFrame:CGRectMake(2*ScrollView_Width, 0, ScrollView_Width, ScrollView_Height)];
        _rightImage.backgroundColor = [UIColor blackColor];
    }
    return _rightImage;
}


- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        _pageControl.bounds = CGRectMake(0, 0, CGRectGetWidth(self.bounds), 60);
        _pageControl.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMaxY(self.scrollView.frame) - CGRectGetMidY(_pageControl.bounds));
        // 设置总页数
        _pageControl.numberOfPages = 3;
        // 设置当前页数
        _pageControl.currentPage = 0;
        // 设置总页数指示色
        _pageControl.pageIndicatorTintColor = [UIColor darkGrayColor];
        // 设置当前页数指示色
        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    }
    return _pageControl;
}


@end
